<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2017/11/8
 * Time: 9:23
 */

namespace app\user\controller;

use app\common\controller\BaseController;
use app\user\model\User;
use think\Session;

class Index extends BaseController
{
    protected $model = 'app\user\model\User';

    public  function index()
    {
        return $this->fetch();
    }

    public function _initialize()
    {
    }


    public function checkIn()
    {
        $data=input();
        $userName=$data['username'];
        $passWd=$data['password'];
        $user=$this->M->get(['name'=>$userName]);
        if (!$user){
            return '用户名不存在';
        }else{
            if (!password_verify($passWd,$user->passwd)) {
                return '密码错误';
            }else{
                session('name',$userName);
                return 1;
            }
        }
    }

    public function logout(){
        Session('name',null);
        return ['type'=>1];
    }

    public function get()
    {
        $options = input();
        try {
            $currentUser = Session::get('name');
            $currentUserData = $this->M->get(['name' => $currentUser])->toArray();
            if ($currentUserData['is_admin'] == 1) {
                if (isset($options) && $options!=[]) {
                    $data = $this->M->where($options)->select();
                } else {
                    $data = $this->M->select();
                }
                $a = [];
                foreach ($data as $value) {
                    $a[] = $value->toArray();
                }
                return $a;
            } else {
                return '当前用户无权访问';
            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    public function del(int $id)
    {
        try{
            $currentUser = Session::get('name');
            $currentUserData = $this->M->get(['name' => $currentUser])->toArray();
            $targetUserData = $this->M->get(['id' => $id])->toArray();
            if ($currentUserData['is_admin'] >= $targetUserData['is_admin']) {
                return parent::del($id);
            }else{
                return '没有权限';
            }
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

    public function add($data)
    {
        try{
            $currentUser = Session::get('name');
            $currentUserData = $this->M->get(['name' => $currentUser])->toArray();
            if ($currentUserData['is_admin'] >= $data['is_admin']) {
                return parent::add($data);
            }else{
                return '对不起，当前用户无权添加管理员';
            }
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }

}